package burubaka.service;

import java.util.logging.Logger;

import org.slim3.datastore.Datastore;

import burubaka.common.BurubakaUtil;
import burubaka.common.KeibaNiftyUtil;
import burubaka.common.NetkeibaUtil;
import burubaka.meta.PayOffMeta;
import burubaka.model.PayOff;
import burubaka.model.RaceInfo;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

public class PayOffService {

	private static final Logger log = Logger.getLogger(PayOffService.class.getName());
	private PayOffMeta meta = new PayOffMeta();

	/**
	 * 先祖キー検索
	 * 
	 * @param key
	 * @return List<Key>
	 */
	public PayOff findByAncKey(Key anckey) {
		return Datastore.query(PayOff.class, anckey).asSingle();
	}

	/**
	 * 配当情報を取得する
	 * 
	 * @param text
	 * @return 配当情報
	 * @throws Exception
	 */
	public PayOff getPayOff(RaceInfo raceInfo) throws Exception {
		String text = ResultHorseService.getURLText(raceInfo);
		if (BurubakaUtil.isLocal(raceInfo.getDistrictClass())) {
			return NetkeibaUtil.getPayOff(text);
		}
		return KeibaNiftyUtil.getPayOff(text);
	}

	/**
	 * 登録
	 * 
	 * @param payOff
	 * @return boolean
	 */
	public boolean regist(PayOff payOff) {

		Transaction tx = Datastore.beginTransaction();
		PayOff org = Datastore.query(meta).asSingle();
		if (org != null) {
			payOff.setKey(org.getKey());
		}
		Datastore.put(payOff);
		tx.commit();

		return true;
	}

	/**
	 * 登録
	 * 
	 * @param payOff
	 * @param key
	 *            ancKey
	 * @return boolean
	 */
	public boolean regist(PayOff payOff, Key ancKey) {

		Transaction tx = Datastore.beginTransaction();
		PayOff old = findByAncKey(ancKey);
		Key key = null;
		if (old == null) {
			key = Datastore.allocateId(ancKey, PayOff.class);
		} else {
			key = old.getKey();
		}
		payOff.setKey(key);
		Datastore.put(payOff);
		tx.commit();

		return true;
	}

}
